package com.atguigu.day07;

import org.apache.flink.api.common.eventtime.SerializableTimestampAssigner;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.typeinfo.Types;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.util.Collector;
import org.apache.flink.util.OutputTag;

import java.time.Duration;

public class Example2 {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment
                .getExecutionEnvironment();
        env.setParallelism(1);

        SingleOutputStreamOperator<String> result = env
                .socketTextStream("localhost", 9999)
                .map(r -> Tuple2.of(
                        r.split(" ")[0],
                        Long.parseLong(r.split(" ")[1]) * 1000L
                        )
                )
                .returns(Types.TUPLE(Types.STRING, Types.LONG))
                .assignTimestampsAndWatermarks(
                        WatermarkStrategy.<Tuple2<String, Long>>forBoundedOutOfOrderness(Duration.ofSeconds(0))
                                .withTimestampAssigner(new SerializableTimestampAssigner<Tuple2<String, Long>>() {
                                    @Override
                                    public long extractTimestamp(Tuple2<String, Long> element, long recordTimestamp) {
                                        return element.f1;
                                    }
                                })
                )
                .keyBy(r -> r.f0)
                .process(new KeyedProcessFunction<String, Tuple2<String, Long>, String>() {
                    @Override
                    public void processElement(Tuple2<String, Long> value, Context ctx, Collector<String> out) throws Exception {
                        if (value.f1 <= ctx.timerService().currentWatermark()) {
                            ctx.output(
                                    // 匿名类，侧输出流中的数据类型是String
                                    // 侧输出流的标签是**单例**
                                    new OutputTag<String>("late-event"){},
                                    // 要往侧输出流中发送的数据
                                    "迟到元素：" + value
                            );
                        } else {
                            out.collect("没有迟到的元素：" + value);
                        }
                    }
                });

        result.print("正常数据：");

        // 打印侧输出流的数据
        result
                // 这里的侧输出标签一定要和上面的一样
                .getSideOutput(new OutputTag<String>("late-event"){})
                .print("迟到数据");

        env.execute();
    }
}
